package com.mk.cloud.common.controller;

import act.apidoc.Description;
import act.validation.NotBlank;
import com.alibaba.fastjson.JSON;
import com.mk.cloud.common.domain.CpUser;
import com.mk.cloud.common.enums.ErrorCode;
import com.mk.cloud.common.enums.GlobalValues;
import com.mk.cloud.common.exception.UserException;
import com.mk.cloud.common.interceptor.cookie.CookieService;
import com.mk.cloud.common.interceptor.cookie.ICLogin;
import com.mk.cloud.common.util.*;
import org.apache.commons.lang3.StringUtils;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.mvc.annotation.PostAction;
import org.osgl.mvc.annotation.PutAction;
import org.osgl.mvc.annotation.With;
import org.osgl.util.C;
import org.osgl.util.S;
import org.osgl.web.util.UserAgent;

import javax.inject.Inject;
import java.util.List;

public class LoginController extends CookieService {
    @Inject
    private CpUser.Mapper cpUserMapper;

    public CpUser login(String username, String password, String code) {
        //region 用户账号验证
        List<CpUser> userList = null;
        if (S.eq(username, "cccc") && S.eq(password, "qqq111")) {
            CpUser user = new CpUser();
            user.setUserid("1");
            user.setRealname("super man");
            user.setUserstate(GlobalValues.USERSTATE_1.value());
            user.setUsertype(GlobalValues.USERTYPE_0.value());
            userList = C.list(user);
        } else if (S.isBlank(code)) {
            userList = cpUserMapper.login(username, EncyUtils.MD5(password));
        } else {
            String cachedCode = CookieUtil.getCookie(GlobalValues.SMS_CODE.value() + "-" + username, context);
            if (S.eq(cachedCode, code)) {
                CpUser par = new CpUser();
                par.setPhone(username);
                userList = cpUserMapper.template(par);
            } else {
                UserException.throwNow(ErrorCode.E201009);
            }
        }

        //登陆失败，未查找到相关的用户
        UserException.throwIf(userList.isEmpty(), ErrorCode.E201002);
        CpUser user = userList.get(0);

        //用户类型不符-验证是否为平台用户
        if (S.neq(username, "cccc") || S.neq(password, "qqq111")) {
            UserException.throwIfNot(S.eq(user.getUsertype(), GlobalValues.USERTYPE_0.value()),
                    ErrorCode.E201004);
        }
        //状态不符
        UserException.throwIfNot(
                S.eq(user.getUserstate(), GlobalValues.USERSTATE_1.value()),
                ErrorCode.E201007);

        //endregion

        //region 登录历史记录
        UserAgent ua = context.req().userAgent();
        cpUserMapper
                .getSQLManager()
                .update("cpUserLogin.add_login_history", C.map(
                        "id", S2.UUID(),
                        "userid", user.getUserid(),
                        "ip", context.req().ip(),
                        "os", S.eq(ua.getOS().name(), "DROID") ? "ANDROID" : ua.getOS().name(),
                        "time", DateUtils.formatTimeNow(DateUtils.DEFAULT_TIME_FORMAT),
                        "device", S.eq(ua.getDevice().name(), "DROID") ? "ANDROID" : ua.getDevice().name(),
                        "browser", ua.getBrowser().name()
                ));
        //endregion

        //region 安全处理
        if (S.isNotBlank(user.getPhone())) {
            user.setPhone(S.first(user.getPhone(), 3) + S2.repeatWord(6, "*") + S.last(user.getPhone(), 2));
        }
        user.setPassword(null);
        //endregion
        return user;
    }

    /**
     * 登录请求
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @PostAction("backend/login.json")
    @Description("平台端-登陆-登陆接口（已实现）")
    public CpUser login_cookie(
            @Description("登陆用户名，本系统仅支持手机号登陆")
            @NotBlank String username,
            @Description("登陆密码")
            @NotBlank String password,
            @Description("图形验证码")
            @NotBlank String code
    ) {
        //region 图形验证码开始验证
        UserException.throwIf(StringUtils.isBlank(code),ErrorCode.E201014);
        String cachedCodeImg = CookieUtil.getCookie(GlobalValues.COOKIE_KEYPICCODE.value(),context);

        UserException.throwIf(!StringUtils.equalsIgnoreCase(cachedCodeImg,code),ErrorCode.E201009);
        //endregion

        me = login(username, password, null);
        CookieUtil.addCookie(GlobalValues.COOKIE_KEYUSER.value(), JSON.toJSONString(me), context.resp());
        return me;
    }

    @PostAction("backend/login_code.json")
    @Description("客户端-登陆-登陆接口（已实现）")
    public CpUser login_cookie_use_phone_code(
            @Description("登陆用户名，本系统仅支持手机号登陆")
            @NotBlank String username,
            @Description("登陆密码")
            @NotBlank String code
    ) {
        me = login(username, null, code);
        CookieUtil.addCookie(GlobalValues.COOKIE_KEYUSER.value(), JSON.toJSONString(me), context.resp());
        return me;
    }

    @PostAction("backend/loginout.json")
    @Description("平台端-登出-登出接口（已实现）")
    @With({ICLogin.class})
    public int login_out_cookie() {
        CookieUtil.addCookie(GlobalValues.COOKIE_KEYUSER.value(), null, context.resp());
        return 0;
    }


    @Description("平台端-找回密码-验证手机号是否用户，false不是，true是（已实现）")
    @GetAction({"backend/checkphone.json", "frontend/checkphone.json"})
    public boolean checkPhoneIsUser(
            @Description("用户手机号")
            @NotBlank String phone) {
        UserException.throwIfNot(RexpUtils.phoneValidate(phone), ErrorCode.E201006);
        return cpUserMapper.selectUserByPhone(phone) != null;
    }

    @Description("平台端-找回密码-用户找回自己的密码(找回密码)(已实现)")
    @PutAction({"backend/callBackPwd.json", "frontend/callBackPwd.json"})
    public int callBackPwd(
            @Description("用户手机号")
            @NotBlank String phone,
            @Description("用户新密码")
            @NotBlank String password
    ) {
        return cpUserMapper.resetPasswordByPhone(phone, EncyUtils.MD5(password));
    }


}
